<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Client extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     * 		http://example.com/index.php/welcome
     * 	- or -  
     * 		http://example.com/index.php/welcome/index
     * 	- or -
     * Since this controller is set as the default controller in 
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see http://codeigniter.com/user_guide/general/urls.html
     */
    public function addUser() {
        if (isset($_REQUEST['userid']) && isset($_REQUEST['access_token'])) {

            $this->processMatching($_REQUEST['access_token'],$_REQUEST['userid']);
        }
        $response = array("message" => 1, "data" => "");
        echo json_encode($response);
    }
    

    public function cronRanking() {
        $users = $this->user->getAllUser();
        foreach($users as $item){
            $this->processMatching($item->access_token,$item->fbuser_id);
        }
        $this->load->view('welcome_message');
    }
    private function processMatching($access_token,$userid){
            $this->facebook->setAccessToken($access_token);
            
            $this->facebook->setExtendedAccessToken();
            $access_token = $this->facebook->getAccessToken();
            $UserInfo = $this->getUserInfo();
           
            if (!$this->user->issetUser($UserInfo[0]['uid'])) {
                $this->user->insertUser($UserInfo[0], $access_token);
            } else {

                $this->user->updateUser($UserInfo[0], $access_token);
            }
            $DataResult = helper_processMatching($access_token, $this);
            $this->storeMatchingData($DataResult, $UserInfo);
    }
    private function storeMatchingData($DataResult) {
        $FriendInfo = $DataResult['FriendInfo'];
        $user_id = $this->user->getIdOfUser($this->facebook->getUser());
        $this->db->trans_begin();
        $count = 1;
        //print_r($DataResult['points']);
        foreach ($DataResult['points'] as $friendid => $point) {
            $FriendInfo[$friendid]['uid'] = $friendid;

            if (!$this->friend->issetFriend($friendid, $user_id[0]->id)) {
                $this->friend->insertFriend($FriendInfo[$friendid], $user_id[0]->id, $point, $count, 0);
            } else {
                $this->friend->updateFriend($FriendInfo[$friendid], $user_id[0]->id, $point, $count, 0);
            }
            $count++;
        }
        $count = 1;
        //store point book
        foreach ($DataResult['pointsbooks'] as $friendid => $point) {
            $FriendInfo[$friendid]['uid'] = $friendid;
            if (!$this->friend->issetFriend($friendid, $user_id[0]->id)) {
                echo "ok";
                $this->friend->insertFriend($FriendInfo[$friendid], $user_id[0]->id, $point, $count, 1);
            } else {
                $this->friend->updateFriend($FriendInfo[$friendid], $user_id[0]->id, $point, $count, 1);
            }
            $count++;
        }
        $count = 1;
        //store point movies
        foreach ($DataResult['pointsmovies'] as $friendid => $point) {
            $FriendInfo[$friendid]['uid'] = $friendid;
            // echo $this->friend->issetFriend($friendid,$user_id[0]->id);
            if (!$this->friend->issetFriend($friendid, $user_id[0]->id)) {
                echo "ok";
                $this->friend->insertFriend($FriendInfo[$friendid], $user_id[0]->id, $point, $count, 2);
            } else {
                $this->friend->updateFriend($FriendInfo[$friendid], $user_id[0]->id, $point, $count, 2);
            }
            $count++;
        }
        $count = 1;
        foreach ($DataResult['pointsmusic'] as $friendid => $point) {
            $FriendInfo[$friendid]['uid'] = $friendid;
            if (!$this->friend->issetFriend($friendid, $user_id[0]->id)) {
                echo "ok";
                $this->friend->insertFriend($FriendInfo[$friendid], $user_id[0]->id, $point, $count, 3);
            } else {
                $this->friend->updateFriend($FriendInfo[$friendid], $user_id[0]->id, $point, $count, 3);
            }
            $count++;
        }
        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            // generate an error... or use the log_message() function to log your error
            echo $this->db->_error_message();
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }
    }

    public function getDataLikes() {
        $LikesArray = array();
        $fql = "SELECT books,movies,music,uid,sex,birthday_date,name FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())";
        $param = array(
            'method' => 'fql.query',
            'query' => $fql,
            'callback' => ''
        );
        $LikesArray = $this->facebook->api($param);
        return $LikesArray;
    }

    public function getUserLikes() {
        return $this->facebook->api('/me?fields=id,books,music,movies,name,gender,birthday');
    }

    public function getUserInfo() {
        $LikesArray = array();
        $fql = "SELECT books,movies,music,uid,sex,birthday_date,name FROM user WHERE uid = me()";
        $param = array(
            'method' => 'fql.query',
            'query' => $fql,
            'callback' => ''
        );
        $LikesArray = $this->facebook->api($param);
        return $LikesArray;
    }

    public function getAge($birthday_date) {
        return floor((time() - strtotime($birthday_date)) / (60 * 60 * 24 * 365));
    }

    private function curl_get_contents($url) {
        // Initiate the curl session
        $ch = curl_init();
        // Set the URL
        curl_setopt($ch, CURLOPT_URL, $url);
        // Removes the headers from the output
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // Return the output instead of displaying it directly
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // Execute the curl session
        $output = curl_exec($ch);
        // Close the curl session
        curl_close($ch);
        // Return the output as a variable
        return $output;
    }

    private function getAccessToken($access_token, $config) {
        $user_token = $access_token;
        $newToken = 'https://graph.facebook.com/oauth/access_token?client_id=' . $config['appId'] . '&client_secret=' . $config['secret'] . '&grant_type=fb_exchange_token&fb_exchange_token=' . $user_token;

        //echo $newToken;
        $buff = $this->curl_get_contents($newToken);
        if ($buff == "") {
            $newToken = file_get_contents($newToken);
        } else {
            $newToken = $buff;
        }


        $newToken = explode("&", $newToken);
        $newToken = $newToken[0];
        $newToken = explode("=", $newToken);
        $newToken = $newToken[1];
        return $newToken;
    }

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */